import { fetchData } from '@/api/_____';

import { valid } from 'mockjs';
import { doPost } from '@/api/_____';
import { log } from '@/utils/log';
// import { getDeptTree } from '@/api/dept';
import { Message } from 'element-ui'
const mixin={
  data() {
      function validateUserName/*用户名验证*/(rule,value,callback){
        const  Regex = /^[a-zA-Z0-9_-]{4,18}$/
        if (Regex.test(value)) { // 使用正则表达式校验用户输入的值，校验成功返回true，否则返回false
          callback() // 放行，说明value值通过了校验
          } else {
          callback(new Error('用户名包含字母、数字、下划线、减号'))
        }
      }
      function validateEmail/*邮箱验证*/(rule,value,callback){
        const Regex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
        // js中，value值为'', undefined, 0, null, 等价于false
        if (value) {
          if (!Regex.test(value)) {
            callback(new Error('邮箱不合法'))
            return
          }
        }
        callback()
      }
      function validatePhone/*电话号码验证*/(role,value,callback){
        const Regex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (value) {
          if (!Regex.test(value)) {
            callback(new Error('手机号码不合法'))
            return
          }
        }
        callback()
      }
      function validatePasword/*密码验证*/(role,value,callback){  
         const Regex = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
         if (value) {
          if (!Regex.test(value)) {
            callback(new Error('必须包含字母、数字、特称字符，至少8个字符'))
            return
          }
        }
        callback()
      }
      return {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        dialogVisible:false,/*弹出对话框*/
        list: [],
        deptTree: [],
        itemBatchData:[],/*多选处理*/
        infoBoxType:"info",/*记录确认消息弹出的类型*/
        infoType:"info",/*记录顶部普通的类型*/
        formInline:{
          <!!!!!----------!!!!!>
        },
        treeData: [{
          label: '一级 1',
          children: [{
            label: '二级 1-1',
            children: [{ label: '三级 1-1-1'}]
          }]
        }, {
          label: '一级 2',
          children: [{
            label: '二级 2-1',
            children: [{label: '三级 2-1-1'}]
          }, {
            label: '二级 2-2',
            children: [{label: '三级 2-2-1'}]
          }]
        }, {
          label: '一级 3',
          children: [{
            label: '二级 3-1',
            children: [{label: '三级 3-1-1'}]
          }, {
            label: '二级 3-2',
            children: [{label: '三级 3-2-1'}]
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        defaultStates: ['所有', '正常', '停用'],
        fromView:{
          type:1,/*请求类型-新增/修改/删除/批量删除*/
          <=====----------=====>
          isFormLoadding: false/*加载等待...*/
        },
        formRules:{
          userName:[
            {required:true,message:"请输入用户账号",trigger:"blur"},
            {min:4,max:18,message:"用户账号4-18位",trigger:"blur"},
            {validator:validateUserName,trigger:"blur"}
          ],
          nickName:[
            {required:true,message:"请输入用户昵称",trigger:"blur"},
          ],
          email:[
          { validator:validateEmail, trigger: 'blur' }
          ],
          phonenumber:[
            { validator:validatePhone, trigger: 'blur' }
          ],
          pasword:[
            {validator:validatePasword,trigger:"blur"}
          ]

        },
        buttonText:{
          editSubmit:"立即创建"
        }
      }
    },

    // vue中的生命周期钩子函数
    // 当前页面本质上就是一个Vue的对象
    // 在这个Vue对象被实例化后，执行created钩子函数
    created() {
      // 发起异步请求，向后端请求数据
      //axios会将结果封装到Promise对象中
      this.fetchList();
      /*查询获取树结构*/
      // getDeptTree().then(resp => {
      //   // 获取服务器返回的数据
      //   this.deptTree = resp.data
      //   console.log("钩子函数",resp.data)
      // })
      console.groupEnd();
    },
    methods:{
          handleSizeChange(pageSize){
            console.log("修改当前显示数量:",pageSize);
            this.pageSize=pageSize
            this.fetchList({pageNum:1,pageSize:this.pageSize})
          },
          handleCurrentChange(pageNum){
            console.log("修改当前页码:",pageNum);
            this.pageNum=pageNum
            this.fetchList({pageNum:this.pageNum,pageSize:this.pageSize})
          },
          handleNodeClick(){
          
          },
          fetchList(params)/*查询函数*/{
            console.log("前端发送请求:",params);
            fetchData(params)
            .then(resp=>{
            const{pageNum,pageSize,total,data} = resp.data
              // 将接收到的来自于服务器的数据保存到data属性中
              console.log("请求结果:",data)
              console.groupEnd();
              this.pageNum = pageNum
              this.pageSize = pageSize
              this.total = total
              this.list = data
            }).catch(error => {console.log("执行异步请求发生错误",error)
            })
          },
          onQuery()/*条件查询执行*/{
            // ... 对象扩展符， 将this.formInline对象中的属性复制到当前params对象中
            const params = { pageNum: 1, pageSize: this.pageSize, ...this.formInline }
            console.log("条件查询",this.formInline)
            // 点击查询按钮
            this.fetchList(params)
          },
          tableSelect(x){
            this.itemBatchData=x
          },
          onSubmitAdd(){
            // 点击立即创建按钮，触发表单提交
            // 在提交表单之前需要校验表单是否通过验证
            this.$refs['fromView'].validate(valid => { // valid是一个buer值
              if (valid) {
                this.fromView.isUserFormLoadding = true
                console.log("提交表单",this.fromView)
                doPost(this.fromView).then(resp => {
                  // console.log(resp)  // {code:20000, message:''}
                  this.messageFun(1,(resp.message ||"操作成功！"))

                  //更新数据
                  this.fetchList();
                  // 隐藏对话框
                  this.dialogVisible = false
                  //重置验证
                  this.resetUserForm()
                })
              }
            })
          },
          handleAdd() /*弹出对话框*/{
            this.dialogVisible = true
          },
          resetUserForm()/*重置表单校验规则*/{
            this.$refs['fromView'].resetFields()
            this.dialogFormVisible = false
            // 清空用户输入的信息
            this.fromView = {
              type:1,/*请求类型-新增/修改/删除/批量删除*/
              <=====----------=====>
              isFormLoadding: false/*记录加载中*/
            }
          },
          closeUserDialog()/*隐藏对话框*/ {
            // 隐藏对话框
            this.dialogFormVisible = false
            // 重置表单
            this.resetUserForm()
          },
          dialogClose()/*关闭当前对话框*/{
            this.dialogVisible = false
            this.resetUserForm()/*重置表单*/
          },
          deleteItem(index,scope,row){
           console.log("正在执行删除:")
           function activeFun(v)/*积极事件*/{
            /*获取主键*/
            doPost({type:2,key:scope.userId}).then(resp => {
              // console.log(resp)  // {code:20000, message:''}
              v.messageFun(1,(resp.message ||"删除成功！"))
              v.fetchList();/*更新数据*/
            })
           }
           function negativeFun()/*消极事件*/{
            console.log(555)
           }

           this.messageBox('提示','此操作将永久删除数据, 是否继续?',2,'确定',activeFun,'取消',negativeFun)
          
          },
          editItem(row){
            this.dialogVisible = true
            this.buttonText.editSubmit="确认修改"
            Array.from(Object.keys(this.fromView)).map(v=>{
              this.fromView[v]=row[v]
            })
            this.fromView["dept_id"]=row["dept"].deptId
            this.fromView["type"]=1
            console.log("正在编辑:",this.fromView)
          },
          /*确认消息*/messageBox(title,info,messagetype,button1,function1,button2,function2){
            if(messagetype==1){ this.infoBoxType="success"}
            if(messagetype==2){ this.infoBoxType="warning"}
            if(messagetype==3){ this.infoBoxType="error"}

            console.log(this.infoBoxType)
            this.$confirm(info, title, {
              confirmButtonText: button1,
              cancelButtonText: button2,
              type: this.infoBoxType
            }).then(() => {
              function1(this)
            }).catch(() => {
              function2(this)        
            });
          },
          /*普通消息*/messageFun(type,info){
            let infoType="info"
            if(type==1){ this.infoType="success"}
            if(type==2){ this.infoType="warning"}
            if(type==3){ this.infoType="error"}
            this.$message({
              type: this.infoType,
              duration: 2 * 1000,
              showClose: true,
              message: info
            });
          },
          /*显示对话框*/showDialog(type){
           if(type==1/*新增*/){
            this.buttonText.editSubmit="立即创建"
            this.dialogVisible = true
           }

          },
          /*table批量删除*/itemBatch_DEL(){
           
           let arr=Array.from(this.itemBatchData).map(v=>{
            return v.userId
           })
           let obj={type:3,list:arr}
           doPost(obj).then(resp => {
            this.messageFun(1,(resp.message ||"删除成功！"))
            this.fetchList();/*更新数据*/
          })
            
          }
    }
}

export default mixin;